package com.crazypos.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazypos.constant.UploadTypeConstant;
import com.crazypos.dao.ProductDao;
import com.crazypos.exceptions.MyException;
import com.crazypos.pojo.ProductEntity;
import com.crazypos.pojo.bo.CreateProductBO;
import com.crazypos.service.IBrandService;
import com.crazypos.service.ICategoryService;
import com.crazypos.service.IProductService;
import com.crazypos.service.IUploadImageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
public class ProductService extends ServiceImpl<ProductDao, ProductEntity> implements IProductService {
    @Autowired
    private ProductDao productDao;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IUploadImageService uploadImageService;

    @Override
    @Transactional
    public void createProduct(CreateProductBO bo, Integer isSystem, String userId, String organizationId) throws IOException {
        String categoryId = bo.getCategoryId();
        int categoryExist = categoryService.getCountByOrzId(categoryId, organizationId);

        if (categoryExist <= 0) {
            throw new MyException(404, "找不到产品分类");
        }

        String brandId = bo.getBrandId();
        int brandExist = brandService.getCountByOrzId(brandId, organizationId);
        if (brandExist <= 0) {
            throw new MyException(404, "找不到产品品牌");
        }


        ProductEntity productEntity = new ProductEntity();
        BeanUtils.copyProperties(bo, productEntity);
        productEntity.setName(bo.getName());
        productEntity.setCreatedBy(userId);
        productEntity.setOrganizationId(organizationId);
        productEntity.setStatus(1);
        productEntity.setIsSystem(isSystem);

//        uploadImageService.uploadImage(bo.getImage(), UploadTypeConstant.PRODUCT, "");
        productDao.insert(productEntity);

        if(bo.getImage() != null){
            String imageUrl = uploadImageService.uploadImage(bo.getImage(), UploadTypeConstant.PRODUCT, productEntity.getId());
            ProductEntity updateProduct = new ProductEntity();
            updateProduct.setId(productEntity.getId());
            updateProduct.setImage(imageUrl);
            productDao.updateById(updateProduct);
        }

    }
}
